package utils.parallelrun;

import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 并发运行模拟类.
 *
 * @author zhangbo
 * @since 1.0.0
 */
public class ParallelRunImitation {
    private static Logger log = LoggerFactory.getLogger(ParallelRunImitation.class);

    // 模拟的并发量
    private int paralleNum = 199;

    private CountDownLatch cdl = new CountDownLatch(1);

    Runnable runMethod;

    /**
     * 并发运行模拟类构造函数.
     *
     * @param paralleNum
     *            并发数
     * @param runMethod
     *            每个线程运行的方法
     */
    public ParallelRunImitation(int paralleNum, Runnable runMethod) {
        super();
        this.paralleNum = paralleNum;
        this.runMethod = runMethod;
    }

    /**
     * 
     * 并发运行
     * 
     * @since 2.0.0
     */
    public void run() {
        for (int i = 0; i < paralleNum; i++) {
            new Thread(new AwaitRunable(i)).start();
        }
        System.out.println("线程启动咯");
        cdl.countDown();// 同时启动
    }

    /**
     * 被阻塞运行的线程运行方法.保证统一起跑点
     * 
     * @author zhangbo
     * @since 1.0.0
     */
    public class AwaitRunable implements Runnable {
        private int index;

        public AwaitRunable(int index) {
            super();
            this.index = index;
        }

        @Override
        public void run() {
            try {
                cdl.await();
                System.out.println("执行线程:" + index);
                runMethod.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        ParallelRunImitation test = new ParallelRunImitation(100, new Runnable() {

            @Override
            public void run() {
                System.out.println("并发执行成功咯");
            }
        });
        test.run();
    }
}
